<template>
	<view class="btn_box flex-column align-center just-center">
		<view class="speech flex-row align-center just-center" v-if="is_touching">
			<text :style="is_cannel?'color:#e55b43':''">{{!is_cannel?'松开发送 上滑取消':'松手 取消发送'}}</text>
		</view>
		<view class="btn_bg">
			<view class="btn flex-row align-end">
				<view class="option flex-row align-center just-start" v-if="isChangePostType">
					<image class="jian" v-if="post_type!='text'" @click="changePostType"></image>
					<image class="yu" v-else @click="changePostType"></image>
				</view>
				<textarea v-if="post_type=='text'" placeholder="发消息..." auto-height confirm-type='send'
					@confirm="handleSend({text:partialResult})" v-model="partialResult" @blur="getTextRange"
					@focus="focusText"></textarea>
				<view class="asr" :class="is_touching&&is_cannel?'asr_red':is_touching&&!is_cannel?'asr_start':''"
					@touchstart.stop.prevent="startRecognize" @touchmove.stop.prevent="astMove"
					@touchend.stop.prevent="endRecognize" v-else>
					<fluctuateVue :is_cannel='is_cannel' v-if="is_touching"></fluctuateVue>
					<text v-else>按住 说话</text>
				</view>
				<view class="option flex-row align-center just-start">
					<image class="emji" @click="isEmoji" v-if="false"></image>
					<image class="add" @click="isFile()"></image>
				</view>
			</view>
		</view>
		<view class="emoji" v-if="false">
			<shinn-xEmoji :show='isShowEmoji' @change="changeEmoji"></shinn-xEmoji>
		</view>
		<view class="file flex-row" v-if="isShowfile">
			<view class="flex-column align-center v-img" @click="chooseMedia('img')">
				<image></image>
				<text>图片</text>
			</view>
			<view class="flex-column align-center v-wenjian" @click="chooseMedia('file')">
				<image></image>
				<text>文件</text>
			</view>
			<view class="flex-column align-center v-video" @click="chooseMedia('video')" v-if="false">
				<image></image>
				<text>视频</text>
			</view>
		</view>
	</view>
</template>

<script>
	import fluctuateVue from './fluctuate.vue'
	import utils from '../common/utils'
	const recorderManager = uni.getRecorderManager();

	export default {
		name: "chat-asr",
		components: {
			fluctuateVue,
		},
		props: {
			isChangePostType: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				post_type: 'text', // 输入类型 语音  文字
				partialResult: '', // 识别出的文字
				touches: {},
				file_url: '',
				is_touching: false, //是否正在录音
				is_cannel: false, //是否取消发送
				isShowEmoji: false,
				isShowfile: false,
				text_cursor: '',
			};
		},
		methods: {
			onShowing() {
				const self = this
				const token = uni.getStorageSync('token')
				console.log(token,'token');
				recorderManager.onStop(function(res) {
					console.log(res, 'res');
          return false
					uni.uploadFile({
						url: "https://wake.wakakawa.com/api/common/upload",
						filePath: res.tempFilePath,
						header: {
							token: token
						}, 
						name: "file",
						success(img) {
							// console.log(img,'img');
							let imgs = JSON.parse(img.data)
							// console.log(imgs,'imgssssssssssssss');
							const audioContext = uni.createInnerAudioContext();
							audioContext.src = imgs.data.fullurl
							audioContext.onCanplay(() => {
								// 获取音频的播放时长（单位：秒）
								// console.log('音频文件时长为：', audioContext.duration + 's');
								self.handleSend({
									text: imgs.data.url,
									type: 'mp3',
									infoshichang:Math.ceil(audioContext.duration)
								})
							});
						},
						fail(err) {
							console.log(err, 'err')
						}
					})
				});
			},
			focusText() {
				this.isShowfile = false
				this.isShowEmoji = false
				this.$emit('emoji', this.isShowEmoji)
				this.$emit('file', this.isShowfile)
			},
			isEmoji() {
				this.isShowfile = false
				this.isShowEmoji = !this.isShowEmoji
				if (this.isShowEmoji) {
					this.post_type = 'text'
				}
				this.$emit('emoji', this.isShowEmoji)
				this.$emit('file', this.isShowfile)
			},
			isFile() {
				this.isShowEmoji = false
				this.isShowfile = !this.isShowfile
				if (this.isShowfile) {
					this.post_type = 'text'
				}
				this.$emit('emoji', this.isShowEmoji)
				this.$emit('file', this.isShowfile)
			},
			// 切换文字 语音
			changePostType() {
				this.focusText()
				this.partialResult = ''
				this.text_cursor = ''
				if (this.post_type == 'text') {
					this.post_type = 'audio'
				} else {
					this.post_type = 'text'
				}
			},
			getTextRange(e) {
				this.text_cursor = e.target.cursor
			},
			changeEmoji(e) {
				let start_str = this.safeSubstring(this.partialResult, 0, this.text_cursor)
				let end_str = this.partialResult.replace(start_str, "")
				this.text_cursor++
				let str = `${start_str}${e}${end_str}`
				this.partialResult = str
			},
			// 开始识别
			async startRecognize(e) {
				// let is_auth = await utils.getAuth('record', 'android.permission.RECORD_AUDIO')
				// if (!is_auth) {
				// 	return
				// }
				this.is_touching = true
				this.is_cannel = false
				utils.vibRateShort()
				this.touches = e.touches
				console.log('开始录音');
				recorderManager.start();
				this.isStart = true
			},
			// 监听滑动 
			astMove(evt) {
				const moveY = evt.touches[0].pageY - this.touches[0].pageY;
				// 垂直移动
				if (moveY < -20) {
					if (this.is_cannel) return
					this.is_cannel = true
					utils.vibRateShort()
				} else {
					if (!this.is_cannel) return
					this.is_cannel = false
					utils.vibRateShort()
				}
			},
			// 结束识别事件
			endRecognize() {
				this.is_touching = false
				utils.vibRateShort()
				console.log('录音结束');
				recorderManager.stop();
				this.isStart = false
				this.onShowing()
			},
			// 提交
			handleSend(obj) {
				this.$emit('post', obj)
				this.partialResult = ''
				this.text_cursor = ''
			},
			// 上传文件
			chooseMedia(type) {
				const that = this
				if (type == 'img') {
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], //从相册选择
						success: async function(res) {
							let tempFiles = res.tempFiles
          		let tempFilePaths = res.tempFilePaths
							uni.uploadFile({
								url: `${that.$imgUrl}/api/common/upload`,
								filePath: tempFilePaths[0],
								header: {
									token: uni.getStorageSync('token')
								},
								name: "file",
							}).then(res => {
								let data = JSON.parse(res.data)
								if(data.code==1){
									that.handleSend({
										text: data.data.fullurl,
										type: 'img'
									})
								}else{
									uni.showToast({
										icon:'none',
										title: data.msg||'系統異常'
									})
								}
							})
						}
					})
				} else if(type=='video'){
          return false
					uni.chooseVideo({
						sourceType: ['camera', 'album'],
						success: async function(res) {
							let img = await api.uploadFile({
								file_name: 'file',
								file: res.tempFilePath
							})
							that.handleSend({
								text: img.data.url,
								type: 'video'
							})
						}
					})
				}else if(type=='file'){
					uni.chooseFile({
						count:1,
						extension: ['.pdf'],//文件類型
						success:res=>{
							let tempFiles = res.tempFiles
							let tempFilePaths = res.tempFilePaths
							uni.uploadFile({
								url: `${that.$imgUrl}/api/common/upload`,
								filePath: tempFilePaths[0],
								header: {
									token: uni.getStorageSync('token')
								},
								name: "file",
							}).then(res => {
								let data = JSON.parse(res.data)
								if(data.code==1){
									that.handleSend({
										text: data.data.fullurl,
										type: 'file'
									})
								}else{
									uni.showToast({
										icon:'none',
										title: data.msg||'系統異常'
									})
								}
							})
						}
					})
				}
			},
			safeSubstring(str, start, length) {
				var end = start + length;
				var result = "";
				var emojiFlag = false;
				for (var i = start; i < end; i++) {
					var charCode = str.charCodeAt(i);
					if (charCode >= 0xd800 && charCode <= 0xdbff) {
						// 处理高位代理项
						emojiFlag = true;
					} else if (charCode >= 0xdc00 && charCode <= 0xdfff) {
						// 处理低位代理项
						emojiFlag = false;
					}
					result += String.fromCharCode(charCode);
				}
				if (emojiFlag) {
					// 如果最后一个字符是高位代理项，则需要再次截取一个字符
					result = this.safeSubstring(str, start, length + 1);
				}
				return result;
			}
		}
	}
</script>

<style scoped lang="less">
	.btn_box {
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 9;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.speech {
			width: 100%;
			height: 300rpx;
			background: #fff;
			border-top-left-radius: 100%;
			border-top-right-radius: 100%;
			position: relative;
			box-shadow: 0px -120px 60px 20px rgba(0, 0, 0, 0.1);
		}

		.btn_bg {
			width: 100%;
			background: #fff;
		}

		.btn {
			width: calc(100vw - 80rpx);
			border-radius: 30rpx;
			position: relative;
			margin: 20rpx auto;
			overflow: hidden;

			textarea,
			.asr {
				flex: 1;
				height: 79rpx;
				background: #f8f8f8;
				border-radius: 24rpx;
				padding: 21rpx 30rpx;
				font-size: 28rpx;
				color: #333;
				margin-right: 20rpx;
				box-sizing: border-box;
			}

			.asr {
				line-height: 80rpx;
				text-align: center;
				padding: 0;
			}

			.asr_start {
				background: #EADEFF;
			}

			.asr_red {
				background: #e55b43;
			}

			.option {
				margin-bottom: 18rpx;

				image {
					width: 50rpx;
					height: 50rpx;
					margin-right: 20rpx;
				}

				.jian {
					background: url('../static/images/icon/keywords.png') center no-repeat;
					background-size: 50rpx;
				}

				.yu {
					background: url('../static/images/icon/speech.png') center no-repeat;
					background-size: 50rpx;
				}

				.add {
					background: url('../static/images/icon/fileadd.png') center no-repeat;
					background-size: 50rpx;
					margin-right: 0;
				}

				.emji {
					background: url('../static/images/icon/emji.png') center no-repeat;
					background-size: 50rpx;
				}
			}
		}

		.file {
			width: 100%;
			height: 228rpx;
			padding: 30rpx 60rpx;
			box-sizing: border-box;
			background: #fff;
			border-top: 2rpx solid #f8f8f8;

			view {
				margin-right: 50rpx;

				image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 24rpx;
					background: #f8f8f8 url(../static/images/icon/imgfile.png) no-repeat center;
					background-size: 60rpx 52rpx;
				}

				text {
					font-weight: 400;
					font-size: 28rpx;
					margin-top: 20rpx;
					color: #666666;
				}
			}

			view.v-video image {
				background: #f8f8f8 url(../static/images/icon/videofile.png) no-repeat center;
				background-size: 60rpx 52rpx;
			}
			view.v-wenjian image {
				background: #f8f8f8 url(../static/images/icon/file-wenjian.png) no-repeat center;
				background-size: 60rpx 52rpx;
			}
		}
	}
</style>
